package command.client;

import client.ClientSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.MessageCommunication;
import model.User;

public class AcceptInvitationClient implements CommandClient {

    private String conversationID;

    public AcceptInvitationClient() {
    }

    public void setConversationID(String idOfTheConversation) {
        conversationID = idOfTheConversation;
    }

    @Override
    public void execute(ClientSession clientSession, boolean isInvokedByTheServer) {
        try {
            if (isInvokedByTheServer) {
                MessageCommunication message = (MessageCommunication) clientSession.getObjectInputStream().readObject();
                Object o = clientSession.getObjectInputStream().readObject();
                ArrayList<User> usersActive = (ArrayList<User>) o;
                if (clientSession.getGUIChatPrincipal().getConversations().containsKey(message.getMessage())) {
                    clientSession.getGUIChatPrincipal().getConversations().
                            get(message.getMessage()).updateUserChatList(usersActive);
                } else {
                    clientSession.getGUIChatPrincipal().newGUIChatWindow(message.getMessage(), usersActive);
                }
            } else {
                clientSession.getObjectOutputStream().writeObject(new MessageCommunication(true, "acceptinvitationserver"));
                clientSession.getObjectOutputStream().flush();
                clientSession.getObjectOutputStream().writeObject(new MessageCommunication(true, conversationID));
                clientSession.getObjectOutputStream().flush();
                clientSession.getObjectOutputStream().writeObject(clientSession.getUserSession());
                clientSession.getObjectOutputStream().flush();
            }
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(AcceptInvitationClient.class.getName()).log(Level.SEVERE,
                    "Fallo al ejecutar el comando de aceptar invitación en el cliente", ex);
        }
    }
}
